package com.anandsoftware.service.impl;

import java.util.HashMap;
import java.util.Map;

import com.anandsoftware.application.ApplicationContext;
import com.anandsoftware.security.SecurityAlgorithm;
import com.anandsoftware.security.SecurityUtil;
import com.anandsoftware.security.impl.BlowFish;
import com.anandsoftware.service.UpdateService;
import com.google.gson.Gson;

public class UpdateServiceImpl extends BaseServiceImpl implements UpdateService {

	/**
	 * @param myID
	 *            id of a software
	 * @return returns map of changed properties that are updated on server and
	 *         allowed to be downloaded.
	 */
	@Override
	public Map<String, String> downloadUpdate(String myID, String key) {
		// TODO Auto-generated method stub
		Map<String, String> updates = new HashMap<String, String>();
		String responceText = sendPostRequest(
				ApplicationContext.REQUEST_ACCESS_TOKEN + myID + "&"
						+ ApplicationContext.UPDATE_SERVICE_TOKEN,
				UPDATE_SERVICE_REQUEST_URL);

		BlowFish blowFish = SecurityUtil
				.getInstance(SecurityAlgorithm.BLOWFISH);
		blowFish.setIv(ApplicationContext.DEFAULT_IV);
		blowFish.setKey(key);
		String plainUpdates = blowFish.decrypt(responceText);
		// System.out.println(plainUpdates);
		try {
			updates = new Gson().fromJson(plainUpdates.trim(), HashMap.class);
		} catch (Exception e) {
			System.out.println("ERROR: Can't Download Updates");
			e.printStackTrace();
		}
		return updates;
	}

}
